/**
* @author attilax 1466519819@qq.com
* @version  c0
* Copyright 2013 attilax reserved.
* All content (including but not limited to text, pictures, etc.) have copyright restrictions, the note license.
* all the software source code  copyright belongs to the original owner.
* Creative Commons protocol use please follow the "sign for non-commercial use consistent"; we do not welcome the large-scale duplication, and all rights reserved.
* Commercial sites or unauthorized media may not copy software source code.
**/
 
 


 
package com.mijie.homi.search.service.topic;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wltea.analyzer.lucene.IKAnalyzer;
import org.wltea.analyzer.lucene.NatureAttribute;

import com.mijie.homi.common.constant.MCKey;
import com.mijie.homi.search.dao.topic.TopicDao;
import com.mijie.homi.search.domain.topic.Topic;
import com.mijie.homi.search.domain.topic.TopicOptions;
import com.mijie.homi.search.service.MemcacheService;
import com.mijie.homi.search.service.user.UserService;

@Service
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
public class TopicService {

	@Autowired
	private TopicDao dao;
	@Autowired
	private UserService userService;
	@Autowired
	private MemcacheService mcs;
	
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
	public Topic getTopicById(int id){
		return dao.getTopicById(id);
	}
	
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
	public List<TopicOptions> listOptions(int topicId){
		return dao.listOptions(topicId);
	}
	
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
	public List<Topic> listTopic(int offset,int limit){
		return dao.listTopic(offset, limit);
	}
	
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
	public void clearTrash(){
		List<Integer> list =  dao.listTopicFromTrash();
		for(Integer id : list){
			deleteTopic(id);
		}
	}
	
	@Transactional(rollbackFor={Exception.class})
/**
* @author attilax 1466519819@qq.com
* @version  c0
**/
	private void deleteTopic(int id){
		int succ = dao.deleteTopic(id);
		if(succ==1){
			mcs.delete(MCKey.TOPIC_BY_ID, String.valueOf(id));
			mcs.delete(MCKey.TOPIC_OPTIONS, String.valueOf(id));
			dao.deleteOptions(id);
			List<Integer> userList = dao.listUserForTopicChoice(id);
			for(Integer userId : userList){
				dao.deleteRelatedTopic(userId, id);
				userService.decrNumOfRelatedTopic(userId);
			}
			dao.deleteTopicFromTrash(id);
		}
	}
}